package com.example.demo.app;

import com.example.demo.app.Exception;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.Set;

public class Validator<T> {

    private javax.validation.Validator validator;


    public Validator() {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        this.validator = validatorFactory.getValidator();
    }

    public void validate(T obj) {

        ArrayList<String> errors = new ArrayList<>();
        validator
                .validate(obj)
                .stream()
                .forEach(violation -> errors.add(violation.getMessage()));

        if (!errors.isEmpty()) {
            throw new Exception(StringUtils.join(errors, ","));
        }
    }

    public void validateProperty(T obj, String property) {

        ArrayList<String> errors = new ArrayList<>();

        validator
                .validateProperty(obj, property)
                .stream()
                .forEach(violation -> errors.add(violation.getMessage()));

        if (!errors.isEmpty()) {
            throw new Exception(StringUtils.join(errors, ","));
        }
    }
}
